package com.shijie.service;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.core.ServiceException;
import com.shijie.domain.entity.*;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.domain.enums.EnumInterface.Status;
import com.shijie.mapper.AuthorsMapper;
import com.shijie.mapper.MagazinesMapper;
import com.shijie.mapper.RecommendsMapper;
import com.shijie.mapper.TalentsMapper;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class MagazinesService extends AbstractService<Magazines> {

    @Resource
    private MagazinesMapper magazinesMapper;
    @Resource
    private AuthorsMapper authorsMapper;
    @Autowired
    private ErpUserService erpUserService;
    @Autowired
    private TalentsMapper talentsMapper;

    @Autowired
    private RecommendsMapper recommendsMapper;
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private PictureSynthesisService pictureSynthesisService;

    /**
     * 视界首页内容
     *
     * @param q
     * @param categoryId
     * @param status
     * @param indexType
     * @return
     */
    public List<Magazines> searchForIndex(String q, Integer categoryId, Integer status, EnumInterface.EntityType entityType) {

        Example condition = new Example(Magazines.class);
        Example.Criteria criteria = condition.createCriteria();
        if (StringUtils.isNotBlank(q)) {
            Example.Criteria criteriax = condition.createCriteria();
            criteriax.andLike("title", "%" + q + "%").orLike("categoryName", "%" + q + "%");
            condition.and(criteriax);
        }

/*        if (EnumInterface.IndexType.ORDINARY.equals(indexType)) {
            if (categoryId != null) {
                criteria.andEqualTo("categoryId", categoryId);
            }
            criteria.andEqualTo("isHot", EnumInterface.IsUsed.NOUSED.ordinal());
            criteria.andEqualTo("isLab", EnumInterface.IsUsed.NOUSED.ordinal());
        } else if (EnumInterface.IndexType.HOT.equals(indexType)) {
            if (categoryId != null) {
                criteria.andEqualTo("categoryId", categoryId);
            }
            criteria.andEqualTo("isHot",EnumInterface.IsUsed.USED.ordinal());
        } else if (EnumInterface.IndexType.LABORATORY.equals(indexType)) {
            if (categoryId != null) {
                criteria.andEqualTo("categoryId", categoryId);
            }
            criteria.andEqualTo("isLab", EnumInterface.IsUsed.USED.ordinal());
        }
*/
        if (categoryId != null) {
            criteria.andEqualTo("categoryId", categoryId);
        }

        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        if(entityType != null){
        	criteria.andEqualTo("type", entityType.ordinal());        	
        }
        condition.orderBy("id").desc();

        return magazinesMapper.selectByCondition(condition);
    }

    /**
     * 达人默认为内容列表
     *
     * @param q
     * @param status
     * @return
     */
    public List<Magazines> searchForTalent(String q, Integer status) {
        Example condition = new Example(Magazines.class);
        Example.Criteria criteria = condition.createCriteria();
        if (StringUtils.isNotBlank(q)) {
            Example.Criteria criteriax = condition.createCriteria();
            criteriax.andLike("title", "%" + q + "%").orLike("ownerName", "%" + q + "%");
            condition.and(criteriax);
        }
        criteria.andEqualTo("status", status);
        criteria.andEqualTo("type", EnumInterface.EntityType.TALENT_ARTICLE.ordinal());
        condition.orderBy("id").desc();
        return magazinesMapper.selectByCondition(condition);
    }

    public List<Magazines> getMagazinesListByType(EnumInterface.EntityType entityType, Integer ownerId, Integer status,
                                                  String q) {
        Example condition = new Example(Magazines.class);
        Example.Criteria criteria = condition.createCriteria();
        if (entityType != null) {
            criteria.andEqualTo("type", entityType.ordinal());
        }
        if (ownerId != null) {
            criteria.andEqualTo("ownerId", ownerId);
        }
        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        if (StringUtils.isNotBlank(q)) {
            Example.Criteria criteriax = condition.createCriteria();
            criteriax.andLike("title", "%" + q + "%").orLike("ownerName", "%" + q + "%");
            condition.and(criteriax);
        }
        condition.orderBy("id").desc();
        return magazinesMapper.selectByCondition(condition);
    }


    public void save(Magazines magazine) {
        if ((magazine.getType() == EnumInterface.EntityType.MAGAZINES.ordinal()) || magazine.getType() == EnumInterface.EntityType.ACTIVITY.ordinal()) {
            Authors author = authorsMapper.selectByPrimaryKey(magazine.getOwnerId());
            if (author == null) {
                throw new ServiceException("作者编号%d不存在，请重新选择作者!");
            }
            magazine.setOwnerName(author.getName());
            magazine.setOwnerLogo(author.getAvatar());
        } else if (magazine.getType() == EnumInterface.EntityType.TALENT_ARTICLE.ordinal()) {
            Users user = talentsMapper.detailForTalents(magazine.getOwnerId());
            magazine.setOwnerName(user.getTrueName() == null ? user.getNickName() : user.getTrueName());
            magazine.setOwnerLogo(user.getHeadImg());
        }
        if (magazine.getStatus() == EnumInterface.Status.VALID.ordinal()) {
            magazine.setPublicTime(DateTime.now().toDate());
        }
        if (magazine.getType() == EnumInterface.EntityType.ACTIVITY.ordinal()) {
            Categories cat = categoriesService.selectById(magazine.getCategoryId());
            if (cat != null) {
                magazine.setCategoryName(cat.getName());
                magazine.setCategoryPath(cat.getPath());
            }
        }
        if (magazine.getId() == null) {
            magazine.setActTotal(0);
            magazine.setFavorites(0);
            magazine.setComments(0);
            magazine.setShares(0);
            magazine.setCreateBy(erpUserService.getUserName());
            magazine.setCreateTime(DateTime.now().toDate());
            magazinesMapper.insert(magazine);
        } else {
            magazine.setUpdateBy(erpUserService.getUserName());
            magazine.setUpdateTime(DateTime.now().toDate());
            magazinesMapper.updateByPrimaryKey(magazine);
        }
        pictureSynthesisService.syntherisPicture(magazine);
    }

    public Boolean share(Integer magazineId) {
        Magazines magazine = magazinesMapper.selectByPrimaryKey(magazineId);
        if (magazine != null) {
            Magazines update = new Magazines();
            update.setId(magazine.getId());
            update.setShares(magazine.getShares() + 1);
            magazinesMapper.updateByPrimaryKeySelective(update);
            return true;
        } else {
            return false;
        }
    }

    public void deleteById(Integer id) {
        Recommends r = new Recommends();
        r.setEntityId(id);
        r.setEntityType(2);
        if (recommendsMapper.selectCount(r) > 0) {
            throw new ServiceException("该咨询已加入推荐活动，请先删除推荐信息");
        }
        r.setEntityType(3);
        if (recommendsMapper.selectCount(r) > 0) {
            throw new ServiceException("该咨询已加入推荐活动，请先删除推荐信息");
        }
        Magazines p = new Magazines();
        p.setId(id);
        p.setStatus(Status.CANCEL.ordinal());
        magazinesMapper.updateByPrimaryKeySelective(p);
    }

}
